from django.contrib import admin
from django.db import models as m
import datetime as dt
from bddjango.adminclass import ListDisplayAdmin
from . import models
from .utils import get_statistics_result


# --- 访问记录表
@admin.register(models.Statistics)
class Statics(ListDisplayAdmin):
    list_per_page = 30
    search_fields = ['ip']
    list_filter = ['access_date', 'mobile', 'ip', ]
    readonly_fields = ['access_date', 'access_time']


# --- 流量统计图 ---
@admin.register(models.ViewsByDayModel)
class ViewsByDayAdmin(ListDisplayAdmin):
    list_filter = (
        'access_date',      # 图表过滤字段
    )
    change_list_template = 'admin/admin_test.html'
    default_days = 0        # 启用默认分析天数

    def changelist_view(self, request, extra_context=None):
        response = super().changelist_view(
            request,
            extra_context=extra_context
        )

        try:
            qs: m.QuerySet = response.context_data['cl'].queryset.order_by()
        except (AttributeError, KeyError):
            return response

        if self.default_days and qs.count() == models.Statistics.objects.count():
            days = self.default_days
            print(f'--- 默认查最近{days}天!')
            end_t = dt.datetime.now()
            start_t = end_t - dt.timedelta(days=days)
            qs = models.Statistics.objects.filter(access_date__range=[start_t, end_t]).order_by()
        qs.values()
        qs.filter(access_time__isnull=True)
        qs.filter(access_date__isnull=True)
        data = get_statistics_result(qs)
        # from bddjango import show_ls, show_json
        # for dc in data:
        #     print(dc)
        # show_ls(data)

        response.context_data['date'] = data
        return response


# region 测试区域
from django.utils.html import format_html



# ListDisplayAdmin
# --- 访问记录表
@admin.register(models.Task)
class Task(admin.ModelAdmin):
    """
    在这里我要实现表格预览功能:

    - 每条记录后面加3个按钮, 第一个就是"预览"按钮
    - 点击预览按钮后, 将展示信息
         - [x] 首先填充word模板
         - [x] 将word转换为pdf或html
         - [x] 页面内打开一个layer弹窗
         - [x] 再layer中使用iframe展示pdf
    - 增加按钮后, son[layer中的iframe]和father[父窗口]通信
    """
    change_list_template = 'admin/myLayer.html'
    list_per_page = 5
    list_display = ['id', 'summary', 'content', 'created_at', 'is_pass_audit', 'buttons']
    readonly_fields = ['id']
    search_fields = ['id']
    list_filter = ['is_active']

    def is_pass_audit(self, obj):
        value = '是' if obj.is_active else '否'
        html = f"""
        <p
            class="is_pass_audit_class"
            id="is_pass_audit_{obj.id}"
            style="color: blue; -webkit-user-select: none;"
        >{value}</p>
        """
        # style="border-style:solid;border-width:5px;"

        return format_html(html)
    is_pass_audit.short_description = '通过审核'
    is_pass_audit.allow_tags = True
    is_pass_audit.admin_order_field = 'is_active'


    def buttons(self, obj):
        """<a class="bdChangeButtonClass_{obj.id}" id="bdChangeButtonId_{obj.id}" href="#" onclick="change_obj({obj.id})">编辑</a>"""
        value = '撤销' if obj.is_active else '通过'

        button_style = """cursor:pointer; color: #02c0ce; border: 1px solid #ccc!important; border-radius: 16px!important; -webkit-user-select: none;"""       # 02c0ce        <a>标签蓝色
        button_html = f"""
<div style="display: flex">
    <p
        class="bdPreviewClass_{obj.id}"
        id="bdPreviewButtonId_{obj.id}"
        href="#" 
        onclick="preview_obj({obj.id})"
        style="{button_style}"
    >预览</p>
    &nbsp;
    
    <p
        class="bdChangeButtonClass_{obj.id}"
        id="bdChangeButtonId_{obj.id}"
        href="/api/admin/flow_statistics/task/{obj.id}/change/"
        onclick="change_obj({obj.id})"
        style="{button_style}"
    >编辑</p>
    
    &nbsp;
    <p 
        class="bdActiveButtonClass_{obj.id}"
        id="bdActiveButtonId_{obj.id}"
        onclick="pass_audit_obj({obj.id})"
        style="{button_style}"
    >{value}</p>

</div>
"""

        return format_html(button_html)
    buttons.short_description = "操作"
# endregion


